package org.jeecg.modules.lab.sample.handle.controller;

import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.common.cronJob.MyEnum;
import org.jeecg.common.cronJob.entity.LabCronJob;
import org.jeecg.modules.lab.cronJob.service.ILabCronJobService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.lab.sample.entity.LabSampleHandleList;
import org.jeecg.modules.lab.sample.entity.LabSampleHandle;
import org.jeecg.modules.lab.sample.handle.vo.LabSampleHandlePage;
import org.jeecg.modules.lab.sample.handle.service.ILabSampleHandleService;
import org.jeecg.modules.lab.sample.handle.service.ILabSampleHandleListService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 样品处置表
 * @Author: jeecg-boot
 * @Date:   2023-08-09
 * @Version: V1.0
 */
@Api(tags="样品处置表")
@RestController
@RequestMapping("/handle/labSampleHandle")
@Slf4j
public class LabSampleHandleController {
	@Autowired
	private ILabSampleHandleService labSampleHandleService;
	@Autowired
	private ILabSampleHandleListService labSampleHandleListService;
	@Autowired
	private ILabCronJobService labCronJobService;
	
	/**
	 * 分页列表查询
	 *
	 * @param labSampleHandle
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "样品处置表-分页列表查询")
	@ApiOperation(value="样品处置表-分页列表查询", notes="样品处置表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<LabSampleHandle>> queryPageList(LabSampleHandle labSampleHandle,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<LabSampleHandle> queryWrapper = QueryGenerator.initQueryWrapper(labSampleHandle, req.getParameterMap());
		Page<LabSampleHandle> page = new Page<LabSampleHandle>(pageNo, pageSize);
		IPage<LabSampleHandle> pageList = labSampleHandleService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param labSampleHandlePage
	 * @return
	 */
	@AutoLog(value = "样品处置表-添加")
	@ApiOperation(value="样品处置表-添加", notes="样品处置表-添加")
//    @RequiresPermissions("handle:lab_sample_handle:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody LabSampleHandlePage labSampleHandlePage) {
		LabSampleHandle labSampleHandle = new LabSampleHandle();
		BeanUtils.copyProperties(labSampleHandlePage, labSampleHandle);
		labSampleHandleService.saveMain(labSampleHandle, labSampleHandlePage.getLabSampleHandleListList());

		if (MyEnum.sync) {
			long time = new Date().getTime();
			List<LabCronJob> jobs = new ArrayList<>();
			jobs.add( new LabCronJob("lab_sample_handle", "0", time, 1));
			jobs.add( new LabCronJob("lab_sample_handle_list", "0", time, 2));
			labCronJobService.saveBatch(jobs);
		}
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param labSampleHandlePage
	 * @return
	 */
	@AutoLog(value = "样品处置表-编辑")
	@ApiOperation(value="样品处置表-编辑", notes="样品处置表-编辑")
//    @RequiresPermissions("handle:lab_sample_handle:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody LabSampleHandlePage labSampleHandlePage) {
		LabSampleHandle labSampleHandle = new LabSampleHandle();
		BeanUtils.copyProperties(labSampleHandlePage, labSampleHandle);
		LabSampleHandle labSampleHandleEntity = labSampleHandleService.getById(labSampleHandle.getId());
		if(labSampleHandleEntity==null) {
			return Result.error("未找到对应数据");
		}
		labSampleHandleService.updateMain(labSampleHandle, labSampleHandlePage.getLabSampleHandleListList());

		if (MyEnum.sync) {
			long time = new Date().getTime();
			List<LabCronJob> jobs = new ArrayList<>();
			String condition="handle_id='"+labSampleHandle.getId()+"'";
			jobs.add( new LabCronJob("lab_sample_handle", "1", time, 1));
			jobs.add( new LabCronJob("lab_sample_handle_list", "2",condition, time, 2));
			jobs.add( new LabCronJob("lab_sample_handle_list", "0", time, 3));
			labCronJobService.saveBatch(jobs);
		}
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "样品处置表-通过id删除")
	@ApiOperation(value="样品处置表-通过id删除", notes="样品处置表-通过id删除")
//    @RequiresPermissions("handle:lab_sample_handle:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		labSampleHandleService.delMain(id);

		if (MyEnum.sync) {
			long time = new Date().getTime();
			List<LabCronJob> jobs = new ArrayList<>();
			String condition1="id='"+id+"'";
			String condition2="handle_id='"+id+"'";
			jobs.add( new LabCronJob("lab_sample_handle", "2",condition1, time, 1));
			jobs.add( new LabCronJob("lab_sample_handle_list", "2",condition2, time, 2));
			labCronJobService.saveBatch(jobs);
		}
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "样品处置表-批量删除")
	@ApiOperation(value="样品处置表-批量删除", notes="样品处置表-批量删除")
//    @RequiresPermissions("handle:lab_sample_handle:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.labSampleHandleService.delBatchMain(Arrays.asList(ids.split(",")));

		if (MyEnum.sync) {
			long time = new Date().getTime();
			List<LabCronJob> jobs = new ArrayList<>();
			String[] idList = ids.split(",");
			for (int i = 0; i < idList.length; i++) {
				String condition1="id='"+idList[i]+"'";
				String condition2="handle_id='"+idList[i]+"'";
				jobs.add( new LabCronJob("lab_sample_handle", "2",condition1, time));
				jobs.add( new LabCronJob("lab_sample_handle_list", "2",condition2, time));
			}
			for (int i = 0; i < jobs.size(); i++) {
				jobs.get(i).setOrderNum(i+1);
			}
			labCronJobService.saveBatch(jobs);
		}
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "样品处置表-通过id查询")
	@ApiOperation(value="样品处置表-通过id查询", notes="样品处置表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<LabSampleHandle> queryById(@RequestParam(name="id",required=true) String id) {
		LabSampleHandle labSampleHandle = labSampleHandleService.getById(id);
		if(labSampleHandle==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(labSampleHandle);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "样品处置清单表-通过主表ID查询")
	@ApiOperation(value="样品处置清单表-通过主表ID查询", notes="样品处置清单表-通过主表ID查询")
	@GetMapping(value = "/queryLabSampleHandleListByMainId")
	public Result<List<LabSampleHandleList>> queryLabSampleHandleListListByMainId(@RequestParam(name="id",required=true) String id) {
		List<LabSampleHandleList> labSampleHandleListList = labSampleHandleListService.selectByMainId(id);
		return Result.OK(labSampleHandleListList);
	}


	 /**
	  * 查询待处置的样品
	  *
	  * @return
	  */
	 //@AutoLog(value = "样品处置清单表-通过主表ID查询")
	 @ApiOperation(value="样品处置清单表-待处置的样品", notes="样品处置清单表-待处置的样品")
	 @GetMapping(value = "/queryLabSampleHandleList")
	 public Result<IPage<LabSampleHandleList>> queryLabSampleHandleList() {
		 List<LabSampleHandleList> labSampleHandleListList = labSampleHandleListService.selectSampleList();
		 IPage <LabSampleHandleList> page = new Page<>();
		 page.setRecords(labSampleHandleListList);
		 page.setTotal(labSampleHandleListList.size());
		 return Result.OK(page);
	 }

	 /**
	  *  提交或撤销样品处置
	  *
	  * @param id
	  * @param auditMark
	  * @return
	  */
	 @AutoLog(value = "样品处置表-提交或撤销样品处置")
	 @ApiOperation(value="样品处置表-提交或撤销样品处置", notes="样品处置表-提交或撤销样品处置")
	 @DeleteMapping(value = "/submitOrCancelSampleHandle")
	 public Result<String> submitOrCancelSampleHandle(@RequestParam(name="id",required=true) String id, @RequestParam(name="auditMark", required=true) String auditMark) {
		 labSampleHandleService.submitOrCancelHandle(id,auditMark);

		 if (MyEnum.sync) {
			 long time = new Date().getTime();
			 LabCronJob job=new LabCronJob("lab_sample_handle", "1", time, 1);
			 labCronJobService.save(job);
		 }
		 if(auditMark.equals("审批中")){
			 return Result.OK("提交成功！");
		 }else {
			 return Result.OK("撤销成功！");
		 }

	 }

	 /**
	  *  样品处置审批通过/审批退回
	  *
	  * @param
	  * @return
	  */
	 @AutoLog(value = "样品处置表-样品处置审批通过/审批退回")
	 @ApiOperation(value="样品处置表-样品处置审批通过/审批退回", notes="样品处置表-样品处置审批通过/审批退回")
	 @RequestMapping(value = "/sampleHandleAuditOrBack", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> sampleHandleAuditOrBack(@RequestBody LabSampleHandlePage labSampleHandlePage) {
		 LabSampleHandle labSampleHandle =new LabSampleHandle();
		 BeanUtils.copyProperties(labSampleHandlePage, labSampleHandle);
		 labSampleHandleService.saveOrUpdate(labSampleHandle);

		 if (MyEnum.sync) {
			 long time = new Date().getTime();
			 LabCronJob job=new LabCronJob("lab_sample_handle", "1", time, 1);
			 labCronJobService.save(job);
		 }
		 if(labSampleHandle.getAuditMark().equals("审批通过")){
			 return Result.OK("审批通过!");
		 }else{
			 return Result.OK("退回成功!");
		 }
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param labSampleHandle
    */
//    @RequiresPermissions("handle:lab_sample_handle:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, LabSampleHandle labSampleHandle) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<LabSampleHandle> queryWrapper = QueryGenerator.initQueryWrapper(labSampleHandle, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

     //配置选中数据查询条件
      String selections = request.getParameter("selections");
      if(oConvertUtils.isNotEmpty(selections)) {
           List<String> selectionList = Arrays.asList(selections.split(","));
           queryWrapper.in("id",selectionList);
      }
      //Step.2 获取导出数据
      List<LabSampleHandle>  labSampleHandleList = labSampleHandleService.list(queryWrapper);

      // Step.3 组装pageList
      List<LabSampleHandlePage> pageList = new ArrayList<LabSampleHandlePage>();
      for (LabSampleHandle main : labSampleHandleList) {
          LabSampleHandlePage vo = new LabSampleHandlePage();
          BeanUtils.copyProperties(main, vo);
          List<LabSampleHandleList> labSampleHandleListList = labSampleHandleListService.selectByMainId(main.getId());
          vo.setLabSampleHandleListList(labSampleHandleListList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "样品处置表列表");
      mv.addObject(NormalExcelConstants.CLASS, LabSampleHandlePage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("样品处置表数据", "导出人:"+sysUser.getRealname(), "样品处置表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
//    @RequiresPermissions("handle:lab_sample_handle:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          // 获取上传文件对象
          MultipartFile file = entity.getValue();
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<LabSampleHandlePage> list = ExcelImportUtil.importExcel(file.getInputStream(), LabSampleHandlePage.class, params);
              for (LabSampleHandlePage page : list) {
                  LabSampleHandle po = new LabSampleHandle();
                  BeanUtils.copyProperties(page, po);
                  labSampleHandleService.saveMain(po, page.getLabSampleHandleListList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }

}
